package cn.itcast.interceptor;

import cn.itcast.utils.JwtUtils;
import cn.itcast.utils.TempMap;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取url路径
        String url = request.getRequestURI();

        System.out.println("我是2号---------------------------------------------------");

        //2.判断是否是登录操作
        if (url.contains("login")) {
            log.info("登录操作,直接放行");
            return true;
        }
        //3.如果不是登录操作,那么就需要获取请求头中的令牌
        String token = request.getHeader("token");

        //4.判断令牌是否为null
        if (token == null) {
            log.error("获取到jwt令牌为空,返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401  没有令牌
            return false;
        }

        //5.校验令牌是否正确
        try {
            Claims claims = JwtUtils.parseJWT(token);
            TempMap.put(claims.get("id"));
            log.error("获取到用户id为:" + claims.get("id"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("令牌解析失败,返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        log.info("令牌合法,放行");
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TempMap.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
